import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	PixelRatio, Image, FlatList
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import StorageHelper from '../../../../utils/storageHelper'
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { SearchInput } from '../../../../component/SearchInput.js';
import ModalAreaComponent from '../../../../component/ModalAreaComponent.js';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { SelectMore } from '../../../order/create/_components/SelectMore.js';
import HTTP from '../../../../utils/http';
import { Button } from '../../../../components/form/button';
const scale = GLOBAL.SCALE;
/* 
	params
	isHiddenSwitch : 是隐藏切换 默认 false;
	showAddButton : 是否有添加地址按钮 

*/


export class DeliveryAddress extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		let params = navigation.state.params || {};
		return {
			headerTitle: (
				<Text numberOfLines={1} style={styles.titleStyle}>{params.navTitle || ''}</Text>
			),
			headerTintColor: style.color.dark,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} />,
			headerRight: (params.showAddButton ? <Text style={styles.addBtnText} onPress={() => { params.onpressAdress && params.onpressAdress() }} >添加地址</Text> : null),
			headerStyle: style.headTow.headerStyle
		}
	};

	constructor(props) {
		super(props);
		let { params } = props.navigation.state;
		console.log('params-交货地址', params)
		this.companyId = params.companyId;   /// 做判断 1
		this.companyName = params.companyName;
		//2019-12-16 存储切换用
		this.companyOldId = params.companyId;
		this.companyOldName = params.companyName;
		this.deliveryType = params.deliveryType;  /// 做判断 2
		this.orderType = params.orderType;
		this.type = params.type;
		this.addressType = params.addressType;  /// 做判断 3
		this.tCode = params.tCode || '';
		this.type = params.type || null; // 地址类型 (订单类型 -> order )

		this.pushAddress = [];
		this.state = {
			modalAreaVisible: false,  // 显示隐藏
			areaText: '',
			listData: [],
			status: 'loading',
			loadIcon: false,  // 下拉涮新的 图标
			showAddButton: true, // 新增按钮控制,
			edit: true
		}
		this._getAddressData = this._getAddressData.bind(this);
		this.pageNo = 1;
		this.totalPage = 1;
		this.onrefresh = true;
		this.searchCode = ''
		// 地区选择参数
		this.areaModalProp = {
			cancelPress: () => {
				this.setState({
					modalAreaVisible: false
				});
			},
			confirmPress: (data) => {
				this.setState({
					modalAreaVisible: false
				});
			}
		}
	}

	async componentWillMount() {

		this.userInfo = await this._getUserInfo();

		if (this.tCode != 'C' && this.tCode != 'A') {
			if (this.orderType == 'P') { // 采购
				// srcAddressId - 出库地
				if (this.deliveryType == 'T' && this.addressType == 'srcAddressId') {
					console.log('采购供应商地址');
					this.props.navigation.setParams({
						onpressAdress: this._gotoAddPage,
						showAddButton: this.state.showAddButton,
						navTitle: this.companyName
					})
				} else {
					await this._getConst();
					console.log('采购默认化销')
				}
			}

			if (this.orderType == 'S') { // 销售
				// destAddressId - 目的地
				if ((this.deliveryType == 'S' || this.deliveryType == 'P') && this.addressType == 'destAddressId') {
					console.log('销售供应商地址-1');
					this.props.navigation.setParams({
						onpressAdress: this._gotoAddPage,
						showAddButton: this.state.showAddButton,
						navTitle: this.companyName
					})
				} else if (this.deliveryType == 'S' && this.addressType == 'srcAddressId') {
					console.log('销售供应商地址-2');
					//默认化销
					this.companyId = this.userInfo.companyId;
					this.companyName = this.userInfo.companyName;
					this.props.navigation.setParams({
						onpressAdress: this._gotoAddPage,
						showAddButton: false,
						navTitle: this.companyName
					})
					this.setState({
						edit: false
					})
				} else {
					await this._getConst();
				}
			}

		} else {
			console.log('111111111111111111', this.companyName)
			this.props.navigation.setParams({
				onpressAdress: this._gotoAddPage,
				showAddButton: this.state.showAddButton,
				navTitle: this.companyName
			})
		}

		if (this.tCode == 'GP') {
			this.props.navigation.setParams({
				onpressAdress: this._gotoAddPage,
				showAddButton: false,
				navTitle: this.companyName
			})
		}
		Promise.all([this._getAddressInfo(), this._getAddressData()]).then(data => {
			this.setState({
				status: data[1].rows && data[1].rows.length ? 'data' : 'empty',
			})
		})
	}

	_getUserInfo = async () => {
		//获取用户信息
		let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		if (userInfo) {
			userInfo = JSON.parse(userInfo);
		}
		return userInfo || {};
	}

	// 获取  常量  ->   化销地址写死的常量
	_getConst = async (btnOnoff) => {
		this.companyId = this.userInfo.companyId;
		this.companyName = this.userInfo.companyName;
		this.setState({
			showAddButton: false,
			edit: false
		}, () => {
			this.props.navigation.setParams({
				navTitle: this.companyName,
				onpressAdress: this._gotoAddPage,
				showAddButton: btnOnoff || false
			})
		})
	}


	// 下拉更新函数
	_isLoadRefresh = () => {
		this.pageNo = 1;
		this.onrefresh = false;
		this._getAddressData();
	}

	//上拉加载
	_loadData = () => {
		if (this.totalPage > this.pageNo) {
			this.pageNo++;
			this.onrefresh = false;
			this._getAddressData();
		}
	}


	// 点击地址 地址弹框显示隐藏
	_isShow = () => {
		this.setState({
			modalAreaVisible: !this.state.modalAreaVisible
		});
	}

	//获取 地区数据
	async _getAddressInfo() {
		let mapData = require('../../../../data/map.json');
		this.areaModalProp = {
			addressInfo: mapData.data,
			cancelPress: () => {
				this.setState({
					modalAreaVisible: false
				});
			},
			confirmPress: (data) => {
				const { province, city, area } = data;
				const areaText = `${province.areaName},${city.areaName},${area.areaName}`;
				this.setState({
					modalAreaVisible: false,
					areaText
				});
				this._getAddressData(area.areaId);
			},
		}
		return new Promise((resolve, reject) => {
			resolve(this.addressInfo);
		})

	}

	//获取-交货地址数据
	async _getAddressData(area) {
		let sendData = {
			companyId: this.companyId,   // 判断一
			deliveryType: this.deliveryType, // 判断二
			pageNo: this.pageNo,
			searchCode: this.searchCode
		}
		if (area) {
			sendData.areaCode = area;
		}
		if (this.onrefresh) {
			this.setState({
				status: 'loading'
			})
		}
		if (!this.onrefresh && this.pageNo == '1') {
			this.setState({
				loadIcon: true
			})
		}
		// 成交报告 过滤化销的虚拟库
		if (this.type == 'order' && this.companyId == this.userInfo.companyId) {
			sendData.isVirtual = 0;
		}
		let responseData = await HTTP.POST(API_GENERATE(API.ADDRESS_LIST), sendData);
		if (responseData) {
			this.totalPage = responseData.totalPage;
			//添加额外字段
			responseData.rows.map((item) => {
				item.onOff = false
				return item
			})
			this.setState({
				listData: this.pageNo == '1' ? responseData.rows : this.state.listData.concat(responseData.rows),
				status: responseData.rows.length > 0 ? 'data' : 'empty',
				loadIcon: false
			})
		} else {
			this.setState({
				status: 'error',
				loadIcon: false
			})
		}
		return new Promise((resolve, reject) => {
			resolve(responseData);
		})

	}

	_onErrorPress = () => {
		this.pageNo = 1;
		this.onrefresh = true;
		this._getAddressData();
	}

	// 地址模糊搜索
	searchAddress = (keywords) => {
		this.pageNo = 1;
		this.onrefresh = false;
		this.searchCode = keywords;
		this._getAddressData();
	}


	//勾选地址
	_selectAddress = (index, onOff) => {
		let { pushAddress, listData } = this.state;
		let lsData = listData;
		let addrId = lsData[index].addrId;
		if (!onOff) {
			lsData[index].onOff = false;
			let pushAddressNew = this.pushAddress.filter((item) => {
				return addrId != item.addrId
			})
			this.pushAddress = pushAddressNew;
		} else {  //所有订单地址都是单选 （之前就泉化）
			if (this.tCode) {
				lsData.map(item => {
					item.onOff = false;
				})
				this.pushAddress = [];
			}
			lsData[index].onOff = true;
			this.pushAddress.push(lsData[index]);
			if (this.tCode) {
				this.setState({ listData })
			}
		}
	}

	// 一条数据
	_renderItem(data) {
		// let { detailAddress, companyName, onOff, warehouseName, provinceName, provinceCode, cityName, cityCode, areaName, areaCode, addressName } = data.item;
		let { onOff } = data.item;
		let index = data.index;
		let { edit } = this.state
		return (
			<SelectMore item={data.item} index={index} callback={this._callBall} edit={edit} companyId={this.companyId} refeshBack={this.refeshBack} propsData={this.props} onOff={onOff} />
		)
	}
	refeshBack = () => {
		this.onrefresh = true
		this.pageNo = 1
		this._getAddressData()
	}
	//一条数据点击效果
	_callBall = (index, onoff) => {
		this._selectAddress(index, onoff)
	}

	// 跳新增地址页面
	_gotoAddPage = () => {
		this.props.navigation.navigate('AddAddressPage', {
			companyId: this.companyId,
			refeshBack: () => {
				this.onrefresh = true;
				this.pageNo = 1;
				this._getAddressData();
			}
		});
	}

	//跳供应商
	_selectSupplier = () => {
		this.props.navigation.navigate('SeachSupplierPage', {
			orderType: this.orderType,
			companyName: this.companyOldName,
			deliveryType: this.deliveryType,
			companyId: this.companyOldId,
			type: 'address',
			queryType: 'ORDER_COMPANY_ADDR',
			callBack: data => {
				this.companyId = data.companyId;
				this.companyName = data.companyName;
				this.onrefresh = true;
				this.pageNo = 1;
				this.props.navigation.setParams({
					onpressAdress: this._gotoAddPage,
					showAddButton: data.companyId == this.userInfo.companyId ? false : true,
					navTitle: this.companyName
				})
				this._getAddressData();
			}
		})
	}

	//确认按钮
	_commitCall = () => {
		this.props.navigation.state.params.getAddressCallBack(this.pushAddress);
		this.props.navigation.goBack();
	}

	render() {
		let { isHiddenSwitch } = this.props.navigation.state.params || {};
		const searchLeft = require('../../../../imgs/customer/searchLeft.png');
		let { modalAreaVisible, listData, status } = this.state;
		let areaModalProp = this.areaModalProp;
		return (
			<View style={styles.container}>
				<View style={[styles.topHead, isHiddenSwitch ? { flexDirection: 'row', justifyContent: 'center' } : null]}>
					{/* <View style={{ width: 300 * scale, position: 'relative' }} onPress={() => { this._selectSupplier() }}> */}
					<View style={{ width: 280 * scale, position: 'relative' }}>
						<SearchInput
							placeholder={'仓库地址'}
							inputLeftIcon={searchLeft}
							setKeyWord={(txt) => { this.searchAddress(txt) }}
							onChangeText={(txt) => { }}
							onSubmitEditing={(txt) => { }}
							inputViewStyle={styles.searchStyle}
						/>
						{/* <TouchableOpacity onPress={() => { this._selectSupplier() }} style={{ width: 300 * scale, height: 36 * scale, backgroundColor: '#fff', position: 'absolute', opacity: 0 }}></TouchableOpacity> */}
					</View>
					{/* <TouchableOpacity onPress={() => { this._isShow() }} style={{ flexDirection: 'row', alignItems: 'center' }}>
						<Text style={styles.addressText}>地区</Text>
						<Image source={require('../../../../imgs/global/down.png')} style={{ marginLeft: 5 * scale, width: 7 * scale, height: 4 * scale }} />
					</TouchableOpacity> */}
					{
						!isHiddenSwitch ? <TouchableOpacity onPress={() => { this._selectSupplier() }} style={{ flexDirection: 'row', alignItems: 'center' }}>
							<Image source={require('../../../../imgs/switch.png')} style={{ width: 10 * scale, height: 10 * scale }} />
							<Text style={styles.addressText}>切换企业</Text>
						</TouchableOpacity> : null
					}
				</View>
				{
					status == 'data' ? (
						<View style={styles.listBox}>
							<View style={{ height: '100%' }}>
								<FlatList
									data={listData}
									renderItem={(data) => this._renderItem(data)}
									refreshing={this.state.loadIcon}
									onRefresh={() => { this._isLoadRefresh() }}
									onEndReachedThreshold={1}
									onEndReached={() => { this._loadData() }}
								/>
							</View>
							<View style={styles.btnWarp}>
								<Button text={'确定'} width={300} height={34} onPress={this._commitCall} />
							</View>
						</View>
					) : (<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this._onErrorPress} />)
				}
				{areaModalProp.addressInfo ? <ModalAreaComponent {...areaModalProp} visible={modalAreaVisible} /> : null}

			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.white,
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.gray,
	},
	titleStyle: { flex: 1, marginRight: 20 * scale, textAlign: 'center', fontSize: 16 * scale, color: style.color.dark },
	topHead: {
		height: 36 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		flexDirection: 'row',
		marginTop: 10 * scale,
		marginBottom: 15 * scale
	},
	listBox: {
		flex: 1,
		paddingBottom: 60 * scale,
		position: 'relative'
	},
	itemInfo: {
		fontSize: 13 * scale,
		color: style.color.dark,
	},
	addBtn: {
		flexDirection: 'row',
		justifyContent: 'center',
		marginTop: 22 * scale,
	},
	addBtnText: {
		color: style.color.themeColor,
		fontSize: 13 * scale,
		paddingRight: 15 * scale
	},
	searchStyle: { marginRight: 10 * scale },
	addressText: {
		fontSize: 14 * scale,
		color: style.color.dark,
		marginLeft: 2 * scale
	},
	btnWarp: {
		height: 72 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
	},
})